import { computed, ref } from "vue"
import { ElMessage } from "element-plus"

export interface TableConfig<ItemType> {
  cacheKey: string // 本地缓存的key
  defaultList: ItemType[] // 默认列表
  codeKey?: string // 唯一标识符的key
  pageSize?: number
}

export type AimType = 'add' | 'edit' | 'detail'
const DIALOG_TITLE_MAP: Record<AimType, string> = {
  'add': '新增',
  'edit': '编辑',
  'detail': '详情'
}

/**
 * @deprecated useTable已弃用，请使用 useList 来代替。
 */
export const useTable = <ItemType extends Record<string, any> = Record<string, any>>(config: TableConfig<ItemType>) => {
  const { cacheKey, defaultList, codeKey = 'code', pageSize } = config
  const list = ref<ItemType[]>()

  const pageInfo = ref({
    pageSize: pageSize ?? 10,
    pageNum: 1,
    total: 0
  })

  // 初始化和通用函数 start
  const toCache = (list: ItemType[]) => {
    localStorage.setItem(cacheKey, JSON.stringify(list))
  }

  const init = () => {
    const cachedListStr = localStorage.getItem(cacheKey)
    const cachedList: ItemType[] = cachedListStr ? JSON.parse(cachedListStr) : []
    if (cachedList.length) {
      list.value = cachedList
    } else {
      list.value = defaultList
      toCache(defaultList)
    }
    if (list.value?.length) {
      pageInfo.value.total = list.value?.length
    }
  }
  init()

  // 初始化和通用函数 end

  const activeItem = ref<ItemType>()
  const showDialog = ref(false)

  const aim = ref<AimType>('edit')

  const dialogTitle = computed(() => {
    return DIALOG_TITLE_MAP[aim.value]
  })

  const toDetail = (info: ItemType) => {
    aim.value = 'detail'
    showDialog.value = true
    activeItem.value = info
  }

  const toEdit = (info: ItemType) => {
    aim.value = 'edit'
    showDialog.value = true
    activeItem.value = info
  }

  const handleEdit = (form: ItemType) => {
    if (!list.value) {
      list.value = []
    }
    const index = list.value.findIndex(each => each[codeKey] === form[codeKey])

    if (index !== -1) {
      list.value[index] = form
    }
    toCache(list.value)
    showDialog.value = false
  }

  const toAdd = () => {
    aim.value = 'add'
    showDialog.value = true
    activeItem.value = undefined
  }

  const handleAdd = (form: ItemType) => {
    const isRepeat = list.value?.some(each => each[codeKey] === form[codeKey])
    if (isRepeat) {
      return ElMessage.error('唯一标识符不可重复!')
    }
    if (!list.value) {
      list.value = []
    }
    list.value.push(form)
    toCache(list.value)
    showDialog.value = false
  }

  const handleConfirm = (form: ItemType) => {
    if (aim.value === 'detail') {
      showDialog.value = false
      return
    }

    if (aim.value === 'add') {
      handleAdd(form)
    }

    if (aim.value === 'edit') {
      handleEdit(form)
    }

  }

  return {
    aim,
    list,
    activeItem,
    showDialog,
    dialogTitle,
    toEdit,
    toAdd,
    toDetail,
    handleEdit,
    handleConfirm,
    handleAdd,
    pageInfo
  }
}